using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;

namespace MatrixFramework.Shared.Domain.Photos.Tags
{
    /// <summary>
    /// 照片标签实体
    /// 用于照片的分类、标记和检索
    /// </summary>
    public class PhotoTag : FullAuditedAggregateRoot<Guid>, IMultiTenant
    {
        /// <summary>
        /// 租户ID
        /// </summary>
        public virtual Guid? TenantId { get; protected set; }

        /// <summary>
        /// 标签名称
        /// </summary>
        [Required]
        [MaxLength(100)]
        public virtual string Name { get; protected set; }

        /// <summary>
        /// 标签显示名称
        /// </summary>
        [Required]
        [MaxLength(200)]
        public virtual string DisplayName { get; protected set; }

        /// <summary>
        /// 标签描述
        /// </summary>
        [MaxLength(1000)]
        public virtual string Description { get; protected set; }

        /// <summary>
        /// 标签类型
        /// </summary>
        public virtual TagType Type { get; protected set; }

        /// <summary>
        /// 标签分类
        /// </summary>
        [MaxLength(100)]
        public virtual string Category { get; protected set; }

        /// <summary>
        /// 标签颜色
        /// </summary>
        [MaxLength(20)]
        public virtual string Color { get; protected set; }

        /// <summary>
        /// 标签图标
        /// </summary>
        [MaxLength(100)]
        public virtual string Icon { get; protected set; }

        /// <summary>
        /// 父标签ID（支持层级标签）
        /// </summary>
        public virtual Guid? ParentId { get; protected set; }

        /// <summary>
        /// 标签路径（基于层级的完整路径）
        /// </summary>
        [MaxLength(500)]
        public virtual string Path { get; protected set; }

        /// <summary>
        /// 层级深度
        /// </summary>
        public virtual int Level { get; protected set; }

        /// <summary>
        /// 排序顺序
        /// </summary>
        public virtual int SortOrder { get; protected set; }

        /// <summary>
        /// 是否为系统标签
        /// </summary>
        public virtual bool IsSystem { get; protected set; }

        /// <summary>
        /// 是否为AI自动生成的标签
        /// </summary>
        public virtual bool IsAutoGenerated { get; protected set; }

        /// <summary>
        /// 是否启用
        /// </summary>
        public virtual bool IsEnabled { get; protected set; }

        /// <summary>
        /// 是否可搜索
        /// </summary>
        public virtual bool IsSearchable { get; protected set; }

        /// <summary>
        /// 是否可手动添加
        /// </summary>
        public virtual bool AllowManualAdd { get; protected set; }

        /// <summary>
        /// 标签使用次数
        /// </summary>
        public virtual int UsageCount { get; protected set; }

        /// <summary>
        /// 最后使用时间
        /// </summary>
        public virtual DateTime? LastUsedTime { get; protected set; }

        /// <summary>
        /// 标签权重（用于排序和推荐）
        /// </summary>
        public virtual double Weight { get; protected set; }

        /// <summary>
        /// 标签置信度（对于AI生成的标签）
        /// </summary>
        public virtual double Confidence { get; protected set; }

        /// <summary>
        /// 同义词列表
        /// </summary>
        public virtual List<string> Synonyms { get; protected set; }

        /// <summary>
        /// 标签规则
        /// </summary>
        public virtual TagRules Rules { get; protected set; }

        /// <summary>
        /// 标签统计信息
        /// </summary>
        public virtual TagStatistics Statistics { get; protected set; }

        /// <summary>
        /// 父标签导航属性
        /// </summary>
        public virtual PhotoTag Parent { get; protected set; }

        /// <summary>
        /// 子标签集合
        /// </summary>
        public virtual ICollection<PhotoTag> Children { get; protected set; }

        /// <summary>
        /// 照片标签关联集合
        /// </summary>
        public virtual ICollection<PhotoTagMapping> PhotoMappings { get; protected set; }

        protected PhotoTag()
        {
            Synonyms = new List<string>();
            Rules = new TagRules();
            Statistics = new TagStatistics();
            Children = new List<PhotoTag>();
            PhotoMappings = new List<PhotoTagMapping>();
        }

        public PhotoTag(
            Guid id,
            string name,
            string displayName,
            TagType type = TagType.Manual,
            string category = null,
            Guid? parentId = null,
            Guid? tenantId = null) : base(id)
        {
            Name = name;
            DisplayName = displayName;
            Type = type;
            Category = category;
            ParentId = parentId;
            TenantId = tenantId;
            IsEnabled = true;
            IsSearchable = true;
            AllowManualAdd = true;
            Weight = 1.0;

            Synonyms = new List<string>();
            Rules = new TagRules();
            Statistics = new TagStatistics();
            Children = new List<PhotoTag>();
            PhotoMappings = new List<PhotoTagMapping>();

            CalculatePathAndLevel();
        }

        /// <summary>
        /// 更新基本信息
        /// </summary>
        public virtual void UpdateBasicInfo(string displayName, string description = null)
        {
            DisplayName = displayName;
            Description = description;
        }

        /// <summary>
        /// 更新标签类型
        /// </summary>
        public virtual void UpdateType(TagType type)
        {
            Type = type;
            IsAutoGenerated = type == TagType.AI || type == TagType.Auto;
        }

        /// <summary>
        /// 更新分类
        /// </summary>
        public virtual void UpdateCategory(string category)
        {
            Category = category;
        }

        /// <summary>
        /// 更新样式
        /// </summary>
        public virtual void UpdateStyle(string color = null, string icon = null)
        {
            Color = color;
            Icon = icon;
        }

        /// <summary>
        /// 移动到新的父标签
        /// </summary>
        public virtual void MoveTo(Guid? newParentId)
        {
            ParentId = newParentId;
            CalculatePathAndLevel();
        }

        /// <summary>
        /// 更新排序顺序
        /// </summary>
        public virtual void UpdateSortOrder(int sortOrder)
        {
            SortOrder = sortOrder;
        }

        /// <summary>
        /// 设置系统标签状态
        /// </summary>
        public virtual void SetSystemTag(bool isSystem)
        {
            IsSystem = isSystem;
        }

        /// <summary>
        /// 启用/禁用标签
        /// </summary>
        public virtual void SetEnabled(bool isEnabled)
        {
            IsEnabled = isEnabled;
        }

        /// <summary>
        /// 设置可搜索状态
        /// </summary>
        public virtual void SetSearchable(bool isSearchable)
        {
            IsSearchable = isSearchable;
        }

        /// <summary>
        /// 设置手动添加权限
        /// </summary>
        public virtual void SetAllowManualAdd(bool allowManualAdd)
        {
            AllowManualAdd = allowManualAdd;
        }

        /// <summary>
        /// 增加使用次数
        /// </summary>
        public virtual void IncrementUsageCount()
        {
            UsageCount++;
            LastUsedTime = DateTime.Now;
            UpdateStatistics();
        }

        /// <summary>
        /// 减少使用次数
        /// </summary>
        public virtual void DecrementUsageCount()
        {
            UsageCount = Math.Max(0, UsageCount - 1);
            UpdateStatistics();
        }

        /// <summary>
        /// 更新权重
        /// </summary>
        public virtual void UpdateWeight(double weight)
        {
            Weight = Math.Max(0, weight);
        }

        /// <summary>
        /// 更新置信度
        /// </summary>
        public virtual void UpdateConfidence(double confidence)
        {
            Confidence = Math.Max(0, Math.Min(1, confidence));
        }

        /// <summary>
        /// 更新同义词
        /// </summary>
        public virtual void UpdateSynonyms(List<string> synonyms)
        {
            Synonyms = synonyms ?? new List<string>();
        }

        /// <summary>
        /// 添加同义词
        /// </summary>
        public virtual void AddSynonym(string synonym)
        {
            if (!string.IsNullOrWhiteSpace(synonym) && !Synonyms.Contains(synonym))
            {
                Synonyms.Add(synonym);
            }
        }

        /// <summary>
        /// 移除同义词
        /// </summary>
        public virtual void RemoveSynonym(string synonym)
        {
            Synonyms.Remove(synonym);
        }

        /// <summary>
        /// 更新标签规则
        /// </summary>
        public virtual void UpdateRules(TagRules rules)
        {
            Rules = rules ?? new TagRules();
        }

        /// <summary>
        /// 更新统计信息
        /// </summary>
        public virtual void UpdateStatistics()
        {
            Statistics.UsageCount = UsageCount;
            Statistics.LastUsedTime = LastUsedTime;
            Statistics.WeightedUsageCount = UsageCount * Weight;
            Statistics.PopularityScore = CalculatePopularityScore();
        }

        /// <summary>
        /// 计算路径和层级
        /// </summary>
        private void CalculatePathAndLevel()
        {
            if (ParentId == null)
            {
                Level = 0;
                Path = Name;
            }
            else
            {
                Level = 1;
                Path = $"{ParentId}/{Name}";
            }
        }

        /// <summary>
        /// 设置完整路径信息（由服务层调用）
        /// </summary>
        public virtual void SetPathInfo(string fullPath, int level)
        {
            Path = fullPath;
            Level = level;
        }

        /// <summary>
        /// 计算流行度评分
        /// </summary>
        private double CalculatePopularityScore()
        {
            double score = UsageCount * Weight;

            // 最近使用的标签获得额外加分
            if (LastUsedTime.HasValue)
            {
                var daysSinceLastUse = (DateTime.Now - LastUsedTime.Value).TotalDays;
                if (daysSinceLastUse < 7)
                    score *= 1.5;
                else if (daysSinceLastUse < 30)
                    score *= 1.2;
            }

            return score;
        }

        /// <summary>
        /// 检查是否可以删除
        /// </summary>
        public virtual bool CanDelete()
        {
            return !IsSystem;
        }

        /// <summary>
        /// 检查是否可以添加子标签
        /// </summary>
        public virtual bool CanAddChildTag()
        {
            return Level < 5; // 限制最大层级为5
        }

        /// <summary>
        /// 检查名称是否匹配（包括同义词）
        /// </summary>
        public virtual bool IsNameMatch(string searchName)
        {
            if (string.Equals(Name, searchName, StringComparison.OrdinalIgnoreCase))
                return true;

            if (string.Equals(DisplayName, searchName, StringComparison.OrdinalIgnoreCase))
                return true;

            return Synonyms.Any(s => string.Equals(s, searchName, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// 获取显示文本
        /// </summary>
        public virtual string GetDisplayText()
        {
            return string.IsNullOrEmpty(DisplayName) ? Name : DisplayName;
        }

        /// <summary>
        /// 获取完整的层级路径显示文本
        /// </summary>
        public virtual string GetFullPathDisplayText()
        {
            return string.IsNullOrEmpty(Path) ? GetDisplayText() : Path.Replace("/", " > ");
        }
    }

    /// <summary>
    /// 标签类型枚举
    /// </summary>
    public enum TagType
    {
        /// <summary>
        /// 手动标签
        /// </summary>
        Manual = 0,

        /// <summary>
        /// AI标签
        /// </summary>
        AI = 1,

        /// <summary>
        /// 自动标签
        /// </summary>
        Auto = 2,

        /// <summary>
        /// 系统标签
        /// </summary>
        System = 3,

        /// <summary>
        /// 地理标签
        /// </summary>
        Geographic = 4,

        /// <summary>
        /// 时间标签
        /// </summary>
        Temporal = 5,

        /// <summary>
        /// 人物标签
        /// </summary>
        Person = 6,

        /// <summary>
        /// 事件标签
        /// </summary>
        Event = 7,

        /// <summary>
        /// 情感标签
        /// </summary>
        Emotion = 8,

        /// <summary>
        /// 风格标签
        /// </summary>
        Style = 9,

        /// <summary>
        /// 内容标签
        /// </summary>
        Content = 10
    }

    /// <summary>
    /// 标签规则
    /// </summary>
    public class TagRules
    {
        /// <summary>
        /// 最大使用次数限制
        /// </summary>
        public int? MaxUsageCount { get; set; }

        /// <summary>
        /// 最小置信度阈值
        /// </summary>
        public double MinConfidenceThreshold { get; set; } = 0.5;

        /// <summary>
        /// 是否允许重复
        /// </summary>
        public bool AllowDuplicate { get; set; } = false;

        /// <summary>
        /// 是否为互斥标签
        /// </summary>
        public bool IsExclusive { get; set; } = false;

        /// <summary>
        /// 互斥标签列表
        /// </summary>
        public List<Guid> ExclusiveTagIds { get; set; } = new();

        /// <summary>
        /// 必需标签列表
        /// </summary>
        public List<Guid> RequiredTagIds { get; set; } = new();

        /// <summary>
        /// 自动应用条件
        /// </summary>
        public List<TagAutoApplyRule> AutoApplyRules { get; set; } = new();

        /// <summary>
        /// 过期规则
        /// </summary>
        public TagExpirationRule ExpirationRule { get; set; }

        /// <summary>
        /// 验证规则
        /// </summary>
        public List<TagValidationRule> ValidationRules { get; set; } = new();
    }

    /// <summary>
    /// 标签自动应用规则
    /// </summary>
    public class TagAutoApplyRule
    {
        /// <summary>
        /// 条件类型
        /// </summary>
        public TagConditionType ConditionType { get; set; }

        /// <summary>
        /// 条件参数
        /// </summary>
        public Dictionary<string, object> Parameters { get; set; } = new();

        /// <summary>
        /// 置信度阈值
        /// </summary>
        public double ConfidenceThreshold { get; set; } = 0.7;

        /// <summary>
        /// 是否启用
        /// </summary>
        public bool IsEnabled { get; set; } = true;

        /// <summary>
        /// 优先级
        /// </summary>
        public int Priority { get; set; } = 0;
    }

    /// <summary>
    /// 标签条件类型
    /// </summary>
    public enum TagConditionType
    {
        /// <summary>
        /// 文件名包含
        /// </summary>
        FileNameContains = 0,

        /// <summary>
        /// 文件路径包含
        /// </summary>
        FilePathContains = 1,

        /// <summary>
        /// 文件大小范围
        /// </summary>
        FileSizeRange = 2,

        /// <summary>
        /// 创建时间范围
        /// </summary>
        CreationTimeRange = 3,

        /// <summary>
        /// 地理位置范围
        /// </summary>
        LocationRange = 4,

        /// <summary>
        /// 包含其他标签
        /// </summary>
        HasOtherTags = 5,

        /// <summary>
        /// 图片特征匹配
        /// </summary>
        ImageFeatureMatch = 6,

        /// <summary>
        /// 颜色特征
        /// </summary>
        ColorFeature = 7,

        /// <summary>
        /// 人脸检测
        /// </summary>
        FaceDetection = 8,

        /// <summary>
        /// 文字识别
        /// </summary>
        TextRecognition = 9,

        /// <summary>
        /// 自定义条件
        /// </summary>
        CustomCondition = 10
    }

    /// <summary>
    /// 标签过期规则
    /// </summary>
    public class TagExpirationRule
    {
        /// <summary>
        /// 是否启用过期
        /// </summary>
        public bool IsEnabled { get; set; } = false;

        /// <summary>
        /// 过期时间类型
        /// </summary>
        public TagExpirationType ExpirationType { get; set; }

        /// <summary>
        /// 过期时间值
        /// </summary>
        public int ExpirationValue { get; set; }

        /// <summary>
        /// 过期后的操作
        /// </summary>
        public TagExpirationAction ExpirationAction { get; set; }

        /// <summary>
        /// 通知用户
        /// </summary>
        public bool NotifyUser { get; set; } = false;
    }

    /// <summary>
    /// 标签过期类型
    /// </summary>
    public enum TagExpirationType
    {
        /// <summary>
        /// 按天数过期
        /// </summary>
        ByDays = 0,

        /// <summary>
        /// 按使用次数过期
        /// </summary>
        ByUsageCount = 1,

        /// <summary>
        /// 按最后使用时间过期
        /// </summary>
        ByLastUsedTime = 2,

        /// <summary>
        /// 永不过期
        /// </summary>
        Never = 3
    }

    /// <summary>
    /// 标签过期操作
    /// </summary>
    public enum TagExpirationAction
    {
        /// <summary>
        /// 自动移除
        /// </summary>
        AutoRemove = 0,

        /// <summary>
        /// 标记为过期
        /// </summary>
        MarkAsExpired = 1,

        /// <summary>
        /// 禁用标签
        /// </summary>
        DisableTag = 2,

        /// <summary>
        /// 通知管理员
        /// </summary>
        NotifyAdmin = 3
    }

    /// <summary>
    /// 标签验证规则
    /// </summary>
    public class TagValidationRule
    {
        /// <summary>
        /// 规则名称
        /// </summary>
        public string RuleName { get; set; }

        /// <summary>
        /// 规则类型
        /// </summary>
        public TagValidationType ValidationType { get; set; }

        /// <summary>
        /// 规则参数
        /// </summary>
        public Dictionary<string, object> Parameters { get; set; } = new();

        /// <summary>
        /// 错误消息
        /// </summary>
        public string ErrorMessage { get; set; }

        /// <summary>
        /// 是否启用
        /// </summary>
        public bool IsEnabled { get; set; } = true;
    }

    /// <summary>
    /// 标签验证类型
    /// </summary>
    public enum TagValidationType
    {
        /// <summary>
        /// 正则表达式验证
        /// </summary>
        Regex = 0,

        /// <summary>
        /// 长度验证
        /// </summary>
        Length = 1,

        /// <summary>
        /// 字符集验证
        /// </summary>
        CharacterSet = 2,

        /// <summary>
        /// 禁用词验证
        /// </summary>
        ForbiddenWords = 3,

        /// <summary>
        /// 自定义验证
        /// </summary>
        Custom = 4
    }

    /// <summary>
    /// 标签统计信息
    /// </summary>
    public class TagStatistics
    {
        /// <summary>
        /// 使用次数
        /// </summary>
        public int UsageCount { get; set; }

        /// <summary>
        /// 加权使用次数
        /// </summary>
        public double WeightedUsageCount { get; set; }

        /// <summary>
        /// 流行度评分
        /// </summary>
        public double PopularityScore { get; set; }

        /// <summary>
        /// 最后使用时间
        /// </summary>
        public DateTime? LastUsedTime { get; set; }

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreationTime { get; set; } = DateTime.Now;

        /// <summary>
        /// 按日期统计的使用次数
        /// </summary>
        public Dictionary<string, int> UsageByDate { get; set; } = new();

        /// <summary>
        /// 按用户统计的使用次数
        /// </summary>
        public Dictionary<string, int> UsageByUser { get; set; } = new();

        /// <summary>
        /// 按照片类型统计的使用次数
        /// </summary>
        public Dictionary<string, int> UsageByPhotoType { get; set; } = new();

        /// <summary>
        /// 推荐次数
        /// </summary>
        public int RecommendationCount { get; set; }

        /// <summary>
        /// 接受推荐次数
        /// </summary>
        public int AcceptedRecommendationCount { get; set; }

        /// <summary>
        /// 推荐接受率
        /// </summary>
        public double RecommendationAcceptanceRate => RecommendationCount > 0
            ? (double)AcceptedRecommendationCount / RecommendationCount
            : 0;
    }
}